package com.ynny.chapter02.controller;

import com.ynny.chapter02.dao.UserDaoImpl;
import com.ynny.chapter02.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

@WebServlet("/register")
public class RegisterController extends HttpServlet{



    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        System.out.println("register");

        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        System.out.println(username);
        System.out.println(pwd);

        User user = new User();
        user.setUserName(username);
        user.setPassword(pwd);

        UserDaoImpl userDao = new UserDaoImpl();

        int i = userDao.insertUser(user);

        if (i > 0){
            //响应数据给前台
            //response  响应对象
            // \让字符 返回文本格式
            Writer writer = response.getWriter();
            writer.write("{\"code\" : 200, \"msg\" : \"success\", \"data\": null}");

        }else {
            Writer writer = response.getWriter();
            writer.write("{\"code\" : 221, \"msg\" : \"register fail\", \"data\": null}");

        }


    }
}
